import React, { PureComponent} from 'react'
import { connect } from 'react-redux'
import Divider from '@/components/Divider'
import LoadMore from '@/components/LoadMore'
import Cover from '@/components/Cover'
import Album from '@/components/Album'
import UserCard from '@/components/UserCard'
import css from './result.module.scss'
import { searchApi } from '@/api'
class SearchResult extends PureComponent {
    constructor(props) {
        super(props)
        this.state = this.initState()
    }

    listRef = React.createRef()

    initState = () => {
        const tabs = [
            { 
                name: '综合', 
                component: 'all',                 
                params: {},
                children: [
                    { name: '默认排序', component: 'defaultOrder', params: {}, url: '/search/getResult', bangumis: [], movies: [] },
                    { name: '播放多', component: 'click', params: { order: 'click', search_type: 'video' } },
                    { name: '新发布', component: 'pubdate', params: { order: 'pubdate', search_type: 'video' } },
                    { name: '弹幕多', component: 'dm', params: { order: 'dm', search_type: 'video' } }
                ] 
            },
            { name: '番剧', component: 'bangumi', params: { search_type: 'media_bangumi', order: 'totalrank' } },
            { name: 'UP主', component: 'user', params: { search_type: 'bili_user', order: 'totalrank' } },
            { name: '影视', component: 'movies', params: { search_type: 'media_ft', order: 'totalrank' } }
        ]
        return {
            currentTab: 'all',
            childCurrentTab: 'defaultOrder',
            tabs: tabs.map((item, index) => {
                return {
                    ...item,
                    id: index,
                    num: 0,
                    currentPage: 1,
                    pageSize: 20,
                    totalPage: 0,
                    list: []
                }
            }),
            childTabs: tabs[0].children.map((item, index) => {
                return {
                    ...item,
                    id: 't' + index,
                    currentPage: 1,
                    pageSize: 20,
                    totalPage: 0,
                    list: []
                }
            })
        }
    }

    handleTab = item => {
        this.setState({
            currentTab: item.component
        }, () => {           
            const { list } = this.getCurrent()
            if (!list.length) {
                this.getData()
            }
        })
    }    

    handleChildTab = item => {
        this.setState({
            childCurrentTab: item.component
        }, () => {
            const { list } = this.getCurrent()
            if (!list.length) {
                this.getData()
            } 
        })
    }

    getCurrent = () => {
        const { tabs, childTabs, currentTab, childCurrentTab } = this.state
        let current
        if (currentTab === 'all') {
            current = childTabs.find(item => item.component === childCurrentTab)
        } else {
            current = tabs.find(item => item.component === currentTab)
        }
        return current
    }

    countTabNum = data => {
        const topTlist = data.top_tlist
        if (topTlist) {
            const { tabs } = this.state
            tabs.forEach(tab => {
                const comp = tab.component
                if (comp === 'bangumi') {
                    tab.num = topTlist.media_bangumi
                } else if (comp === 'user') {
                    tab.num = topTlist.bili_user
                } else if (comp === 'movies') {
                    tab.num = topTlist.media_ft
                }
            })
            this.setState({
                tabs: [...tabs]
            })
        }
    }

    getData = async () => {
        try {
            if (!this.props.searchKeyword) {
                return
            }
            this.startLoading()
            const current = this.getCurrent()
            const { currentTab, childCurrentTab } = this.state            
            const { params, currentPage, pageSize, totalPage, list, url, bangumis, movies } = current            
            const { data } = await searchApi.getSearchResult(url || '/search/byKeyword', {
                keyword: this.props.searchKeyword,
                page: currentPage,
                pagesize: pageSize,
                ...params
            })
            if (data) {            
                const { result, numPages, page } = data
                if (totalPage === 0) {
                    current.totalPage = numPages
                }
                
                if (numPages === 0) {
                    this.complete()
                } else if (currentTab === 'all' && childCurrentTab === 'defaultOrder') {
                    this.countTabNum(data)
                    // 综合-默认排序
                    // 过滤搜索结果里面的视频 番剧 和影视数据
                    const videos = result.find(item => item.result_type === 'video')
                    if (videos) {
                        current.list = [...list, ...videos.data]
                    }
                    const newBangumis = result.find(item => item.result_type === 'media_bangumi')
                    if (newBangumis) {
                        current.bangumis = [...bangumis, ...newBangumis.data]
                    }
                    const newMovies = result.find(item => item.result_type === 'media_ft')
                    if (newMovies) {
                        current.movies = [...movies, ...newMovies.data]
                    }
                    this.setState({
                        childTabs: [...this.state.childTabs]
                    }) 

                } else if (currentTab === 'all' && childCurrentTab !== 'defaultOrder') {
                    // 综合-默认排序
                    current.list = [...list, ...result]
                    this.setState({
                        childTabs: [...this.state.childTabs]
                    })
                } else {
                    // 设置类型排序的数据
                    current.list = [...list, ...result]
                    this.setState({
                        tabs: [...this.state.tabs]
                    })
                }
                if (page === numPages) {
                    this.complete()
                }
            } else {
                this.complete()
            }
        } catch (error) {
            
        } finally {
            this.stopLoading()
        }
    }

    startLoading = () => {
        this.listRef.current && this.listRef.current.startLoading()
    }
    stopLoading = () => {
        this.listRef.current && this.listRef.current.stopLoading()
    }
    complete = () => {
        this.listRef.current && this.listRef.current.complete()
    }

    onRender = (rowData) => {
        const { currentTab } = this.state
        const isBangumi = currentTab === 'bangumi'
        const isUser = currentTab === 'user'
        const isMovies = currentTab === 'movies'
        
        if (isBangumi) {
            return (
                <Album
                    key={rowData.media_id}
                    id={rowData.season_id} 
                    title={rowData.title}
                    pic={rowData.cover}
                    type={rowData.season_type_name}
                />
            )
        } else if (isUser) {
            return (
                <UserCard 
                    key={rowData.mid}
                    id={rowData.mid}
                    pic={rowData.upic}
                    name={rowData.uname}
                    fans={rowData.fans}
                    videos={rowData.videos}
                    sign={rowData.usign}
                />
            )
        } else if (isMovies) {
            return (
                <Album
                    key={rowData.media_id} 
                    id={rowData.season_id}
                    title={rowData.title}
                    area={rowData.areas}
                    actor={rowData.cv}
                    director={rowData.staff}
                    pic={rowData.cover}
                    type={rowData.season_type_name}
                />
            )
        } else {
            return (
                <Cover 
                    key={rowData.bvid} 
                    direction="horizontal"
                    danmaku={rowData.video_review}                
                    {...rowData} 
                />
            )
        }
    }
    
    onReachEnd = () => {
        const { currentTab } = this.state
        const current = this.getCurrent()
        const { totalPage, currentPage } = current
        if (currentPage < totalPage) {
            current.currentPage = currentPage + 1
            if (currentTab === 'all') {
                this.setState({
                    childTabs: [...this.state.childTabs]
                }, () => {
                    this.getData()
                })
            } else {
                this.setState({
                    tabs: [...this.state.tabs]
                }, () => {
                    this.getData()
                })
            }            
        } else {
            this.complete()
        }
    }

    renderHeader = (bangumis, movies) => {
        const { currentTab, tabs } = this.state        
        if (currentTab !== 'all') {
            return null
        } else {
            const hasBangumis = Array.isArray(bangumis) && bangumis.length > 0
            const hasMovies = Array.isArray(movies) && movies.length > 0
            const { childTabs, childCurrentTab } = this.state
            return (
                <>
                    <ul className={css["child-tabs"]}>
                        {
                            childTabs.map(item => {
                                return (
                                    <li 
                                        className={`tab ${childCurrentTab === item.component ? css['active'] : ''}`} 
                                        key={item.id}
                                        onClick={() => this.handleChildTab(item)}
                                    >{item.name}</li>
                                )
                            })
                        }
                    </ul>
                    {
                        hasBangumis && bangumis.map(item => {
                            return (
                                <Album
                                    key={item.media_id}
                                    id={item.season_id} 
                                    title={item.title}
                                    pic={item.cover}
                                    type={item.season_type_name}
                                />
                            )
                        })                    
                    }
                    {
                        hasBangumis && (
                            <Divider className={css["divider"]}>
                                <span onClick={() => this.handleTab(tabs[1])}>查看更多番剧 <i className="fa fa-dropright"></i></span>
                            </Divider>
                        )
                    }
                    {
                        hasMovies && movies.map(item => {
                            return (
                                <Album
                                    key={item.media_id} 
                                    id={item.season_id}
                                    title={item.title}
                                    area={item.areas}
                                    actor={item.cv}
                                    director={item.staff}
                                    pic={item.cover}
                                    type={item.season_type_name}
                                />
                            )
                        })
                    }
                    {
                        hasMovies && (
                            <Divider className={css["divider"]}>
                                <span onClick={() => this.handleTab(tabs[3])}>查看更多影视 <i className="fa fa-dropright"></i></span>
                            </Divider>
                        )
                    }
               </>
            )
        }        
    }

    componentDidMount() {
        this.getData()
    }

    componentDidUpdate(prevProps) {
        if (prevProps.searchKeyword !== this.props.searchKeyword) {
            this.setState({
                currentTab: 'all'
            }, () => {
                this.getData()
            })            
        }
    }

    render() {
        const { tabs, currentTab } = this.state        
        const current = this.getCurrent()
        const { currentPage, pageSize, list, bangumis, movies } = current
        const pageList = list.slice(0, currentPage * pageSize)

        return (
            <div className={css["wrap"]}>
                <ul className="tabs">
                    {
                        tabs.map(item => {
                            return (
                                <li 
                                    key={item.id} 
                                    className={`tab ${currentTab === item.component ? css['active'] : ''}`}
                                    onClick={() => this.handleTab(item)}
                                >
                                    {item.name}
                                    { item.num > 0 && <span>({item.num > 100 ? '99+' : item.num})</span>}
                                </li>
                            )
                        })
                    }
                </ul>
                <div className="tabs-content">                    
                    <LoadMore                    
                        ref={this.listRef}
                        data={pageList} 
                        enableRefresh={false}                    
                        onReachEnd={this.onReachEnd}
                        renderHeader={() => this.renderHeader(bangumis, movies)}
                        renderRow={this.onRender}
                    />
                </div>
            </div>
        )
    }
}

export default connect(
    state => ({ searchKeyword: state.searchKeyword })
)(SearchResult)